package cn.mazexal.examapi.utils;


import cn.mazexal.examapi.common.models.BizException;
import cn.mazexal.examapi.common.models.CustomerError;
import cn.mazexal.examapi.models.bo.AliyunLoginResBO;
import cn.mazexal.examapi.models.enums.PlatformEnum;
import com.aliyun.dypnsapi20170525.models.GetFusionAuthTokenRequest;
import com.aliyun.dypnsapi20170525.models.GetFusionAuthTokenResponse;
import com.aliyun.dypnsapi20170525.Client;
import com.aliyun.dypnsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 阿里云融合登录工具类
 *
 * @author: Mazexal
 * Date: 2025/6/18
 */
@Slf4j
@Component
public class AliyunLoginUtils {

    private Client client;

    @Value("${aliyun.login.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.login.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.login.regionId}")
    private String regionId;

    @Value("${aliyun.login.androidSign}")
    private String androidSign;

    @Value("${aliyun.login.androidPackage}")
    private String androidPackage;

    @Value("${aliyun.login.iosBundleId}")
    private String iosBundleId;

    @Value("${aliyun.login.schemeCode}")
    private String schemeCode;

    @Value("${aliyun.login.androidSchemeCode}")
    private String androidSchemeCode;

    @Value("${aliyun.login.durationSeconds}")
    private Long durationSeconds;

    @PostConstruct
    private void init() throws Exception {
        Config config = new Config()
                .setAccessKeyId(accessKeyId)         // 替换为阿里云账号的AccessKey
                .setAccessKeySecret(accessKeySecret)     // 替换为SecretKey
                .setRegionId(regionId);       // 默认杭州区域
        this.client = new Client(config);
    }

    public String getFusionAuthTokenRequest(PlatformEnum platform) throws Exception {
        GetFusionAuthTokenRequest request = null;
        if (platform == PlatformEnum.ANDROID) {
            // 2. 构建请求参数
            request = new GetFusionAuthTokenRequest()
                    .setSchemeCode(androidSchemeCode)      // 方案Code
                    .setPlatform(platform.getValue())            // 平台
                    .setDurationSeconds(durationSeconds)         // Token有效期秒
                    .setPackageName(androidPackage) // Android包名
                    .setPackageSign(androidSign);      // Android签名
        } else if (platform == PlatformEnum.IOS) {
            request = new GetFusionAuthTokenRequest()
                    .setSchemeCode(schemeCode)      // 方案Code
                    .setPlatform(platform.getValue())            // 平台
                    .setDurationSeconds(durationSeconds)         // Token有效期秒
                    .setBundleId(iosBundleId);// iOS包名
//                    .setResourceOwnerAccount("com.example.app");
        } else {
            log.error("平台参数错误");
            throw new BizException(new CustomerError("500", "不支持的平台"));
        }
        // 3. 调用接口
        try {
            GetFusionAuthTokenResponse response = client.getFusionAuthToken(request);
            if (!response.getBody().success) {
                log.error("调用阿里云获取Token错误: getFusionAuthTokenRequest :{}", response);
                throw new BizException(new CustomerError("500", "调用阿里云获取Token错误"));
            }
            log.info("调用阿里云获取Token成功: getFusionAuthTokenRequest :{}", response);
            // 4. 获取鉴权Token
            return response.getBody().getModel();
        } catch (Exception e) {
            // 错误处理（如限流、权限不足等）
            log.error("调用阿里云获取Token错误: getFusionAuthTokenRequest :", e);
            throw new BizException(new CustomerError("500", "调用阿里云获取Token错误"));
        }
    }


    public AliyunLoginResBO verifyToken(String authToken) throws Exception {
        // 1. 构建请求对象
        VerifyWithFusionAuthTokenRequest request = new VerifyWithFusionAuthTokenRequest().setVerifyToken(authToken);
        // 2. 调用接口
        VerifyWithFusionAuthTokenResponse response = client.verifyWithFusionAuthToken(request);
        log.info("调用阿里云验证Token返回结果: response :{}", response);
        AliyunLoginResBO res = getAliyunLoginResBO(response);
        return res;
    }

    @NotNull
    private static AliyunLoginResBO getAliyunLoginResBO(VerifyWithFusionAuthTokenResponse response) {
        VerifyWithFusionAuthTokenResponseBody body = response.getBody();
        if (body == null) {
            throw new BizException(new CustomerError("500", "登录校验失败"));
        }
        AliyunLoginResBO res = new AliyunLoginResBO();
        if (body.getSuccess()) {
            String mobile = body.getModel().getPhoneNumber();
            //PASS：认证成功；
            //UNKNOWN：认证失败。
            String result = body.getModel().getVerifyResult();//
            Boolean check = "PASS".equals(result);
            res.setMobile(mobile);
            res.setRes(check);
        } else {
            log.error("阿里云登录校验失败: response :{}", response);
            res.setRes(false);
        }
        return res;
    }


}
